package com.example.librarymanagementsystem.config;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import javax.annotation.Resource;
import java.util.HashMap;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/5/10 14:14
 *  利用AOP思想，实现后端数据的统一格式封装
 */
@ControllerAdvice
public class ResponseAdvice implements ResponseBodyAdvice {
    //由于String类型的返回包装有问题，所以采用Jackson单独封装
    //注入ObjectMapper
    @Resource
    private ObjectMapper objectMapper;

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("statusCode",200);
        hashMap.put("msg","");
        hashMap.put("data",body);
        if (body instanceof String){
            try {
                return objectMapper.writeValueAsString(body);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return hashMap;
    }
}
